<template>
  <div style="margin: 0 5px 10px 5px">
    <h4>发表评论</h4>
    <hr />
    <van-cell-group>
      <van-field
        type="textarea"
        placeholder="请输入留言"
        v-model.trim="content"
      />
    </van-cell-group>
    <van-button type="info" @click="addComment">发表评论</van-button>
    <van-list>
      <div v-for="(item, i) in commentList" :key="item.id">
        <div class="title">
          <span>第{{ i + 1 }}楼</span>
          <span>用户: {{ item.user_name }}</span>
          <span>发表时间: {{ item.add_time | formatDate }}</span>
        </div>
        <div class="body">{{ item.content }}</div>
      </div>
    </van-list>
    <van-button
      plain
      hairline
      type="danger"
      @click="loadMore"
      :disabled="isDisabled"
      >加载更多</van-button
    >
  </div>
</template>

<script>
export default {
  props: ['artId'],
  data() {
    return {
      content: '',
      pageIndex: 1,
      commentList: [], // 评论数据
      finished: true,
      isDisabled: false
    }
  },

  created() {
    this.getCommentList() // 获取评论信息
  },

  methods: {
    async getCommentList() {
      var { data } = await this.$http.get(
        `/api/getcomments/${this.artId}?pageindex=${this.pageIndex}`
      )
      if (data.status !== 0) {
        return this.$toast('加载评论列表失败!')
      }
      if (data.message.length === 0) {
        this.isDisabled = true
        return this.$toast('没有更多数据了')
      }
      this.commentList.push(...data.message)
      // console.log(this.commentList)
    },
    loadMore() {
      // 加载更多
      this.pageIndex++ // 改变页数之后，再次获取数据
      this.getCommentList()
    },
    async addComment() {
      // 发表评论
      if (!this.content) return this.$toast('输入内容不能为空!')

      var { data: res } = await this.$http.post(
        `/api/postcomment/${this.artId}`,
        {
          content: this.content
        }
      )
      if (res.status !== 0) {
        return this.$toast('提交评论失败!')
      }
      // 提示用户评论提交成功
      this.$toast(res.message)

      this.commentList.unshift({
        user_name: '匿名用户',
        add_time: new Date(),
        content: this.content
      })
      this.content = '' // 评论提交成功后，输入框清空数据
    }
  }
}
</script>

<style lang="less" scoped>
.van-field {
  height: 100px;
  border: 1px solid #ccc;
}
.van-button {
  width: 100%;
  margin-top: 5px;
  margin-bottom: 5px;
}
.title {
  height: 30px;
  background-color: #ccc;
  font-size: 12px;
  line-height: 30px;
  span {
    margin-right: 6px;
  }
}
.body {
  min-height: 35px;
  line-height: 35px;
  text-indent: 2em;
  font-size: 12px;
  display: block;
  white-space: nowrap; /* 不进行换行 */
  text-overflow: ellipsis; /* 显示省略符号来代表被修剪的文本。*/
  overflow: hidden;
}
</style>
